package cn.xy.third.weixin.service.impl;

import cn.hutool.json.JSONUtil;
import cn.xy.commons.exception.JzRuntimeException;
import cn.xy.commons.util.HttpsUtil;
import cn.xy.commons.util.StringUtil;
import cn.xy.third.weixin.bean.WeixinAppUserInfo;
import cn.xy.third.weixin.bean.WeixinAppUserToken;
import cn.xy.third.weixin.config.WeixinConfig;
import cn.xy.third.weixin.service.WeixinAppService;
import cn.xy.third.weixin.service.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WeixinAppServiceImpl implements WeixinAppService {

    private static final String USER_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";

    private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";

    @Autowired
    WeixinService weixinService;

    @Override
    public WeixinAppUserToken getUserAccessToken(WeixinConfig weixinConfig, String code) {
        String url = USER_ACCESS_TOKEN_URL + "?appid=" + weixinConfig.getAppId() + "&secret=" + weixinConfig.getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
        String json = HttpsUtil.doGet(url);
        log.info("getUserAccessToken get {}", json);
        WeixinAppUserToken accessToken = JSONUtil.toBean(json, WeixinAppUserToken.class);
        if (accessToken == null || accessToken.getErrcode() > 0) {
            throw new JzRuntimeException("微信登录已失效，请重新登录");
        }
        return accessToken;
    }

    @Override
    public WeixinAppUserInfo getUserInfo(String accessToken, String openId) {
        String url = USER_INFO_URL + "?access_token=" + accessToken + "&openid=" + openId;
        String json = HttpsUtil.doGet(url);
        log.info("getUserInfo {}", json);
        WeixinAppUserInfo userInfo = JSONUtil.toBean(json, WeixinAppUserInfo.class);
        if (StringUtil.isEmpty(userInfo.getOpenid()) && StringUtil.isEmpty(userInfo.getUnionid())) {
            throw new JzRuntimeException("微信登录用户信息获取失败");
        }
        return userInfo;
    }

    @Override
    public WeixinAppUserInfo getUserInfo(WeixinConfig weixinConfig, String code) {
        WeixinAppUserToken weixinAppUserToken = this.getUserAccessToken(weixinConfig, code);
        return getUserInfo(weixinAppUserToken.getAccess_token(), weixinAppUserToken.getOpenid());
    }
}
